package com.example.android_sqlite;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.android_sqlite.db.MySQLite;
import com.example.android_sqlite.wieget.ConstantEnum;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    /**
     * 声明控件
     */
    private TextView mMainPromapt;
    private TextView mMainMessage;
    private Button mMainGradeInsert;
    private Button mMainTeachInsert;
    private Button mMainStudentInsert;
    private Button mMainGradeShow;
    private Button mMainTeachShow;
    private Button mMainStudentShow;
    private ListView mMainInfoShow;
    private SQLiteDatabase writaDb;

    // 设配器的声明
    private ShowInfoAdapter adapter;

    /**
     * 声明数据库
     */
    private MySQLite sqLite;

    /**
     * popupWindow展示的视图
     */
    private View showGrade;
    private View showStudent;
    private View showTeacher;
    private AlertDialog gradeDialog, studentDialog, teachDialog;

    /**
     * teach 控件的声明
     */
    private EditText mTeachName;
    private EditText mTeachAge;
    private EditText mTeachSex;
    private EditText mTeachClass;
    private Button mTeachEnter;
    private Button mTeachCancel;

    /**
     * grade 控件的声明
     */
    private EditText mGradeName;
    private EditText mGradeTeach;
    private Button mGradeEnter;
    private Button mGradeCancel;

    /**
     * 学生控件的声明
     * */
    private EditText mStudentName;
    private EditText mStudentAge;
    private EditText mStudentSex;
    private EditText mStudentLike;
    private Button mStudentEnter;
    private Button mStudentCancel;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initActivity();
        setOperation();
        setListener();
    }

    /**
     * 添加监听事件
     */
    private void setListener() {

        /**
         * button 添加监听事件
         */
        mMainGradeInsert.setOnClickListener(this);
        mMainGradeShow.setOnClickListener(this);
        mMainStudentInsert.setOnClickListener(this);
        mMainStudentShow.setOnClickListener(this);
        mMainTeachInsert.setOnClickListener(this);
        mMainTeachShow.setOnClickListener(this);

        mGradeEnter.setOnClickListener(this);
        mGradeCancel.setOnClickListener(this);

        mTeachEnter.setOnClickListener(this);
        mTeachCancel.setOnClickListener(this);

        mStudentEnter.setOnClickListener(this);
        mStudentCancel.setOnClickListener(this);
    }

    /**
     * 控件以及变量的操作
     */
    private void setOperation() {

        // 添加适配器
        mMainInfoShow.setAdapter( adapter);
    }

    /**
     * 初始化控件以及变量
     */
    private void initActivity() {

        /**
         * 初始化控件
         */
        mMainPromapt = findViewById(R.id.main_promapt);
        mMainMessage = findViewById(R.id.main_message);
        mMainGradeInsert = findViewById(R.id.main_grade_insert);
        mMainTeachInsert = findViewById(R.id.main_teach_insert);
        mMainStudentInsert = findViewById(R.id.main_student_insert);
        mMainGradeShow = findViewById(R.id.main_grade_show);
        mMainTeachShow = findViewById(R.id.main_teach_show);
        mMainStudentShow = findViewById(R.id.main_student_show);
        mMainInfoShow = findViewById(R.id.main_info_show);

        /**
         * 适配器的初始化
         */
        adapter = new ShowInfoAdapter();
        /**
         * 初始化数据库
         */
        sqLite = new MySQLite(this, "school.db", null, 1);
        writaDb = sqLite.getWritableDatabase();

        /**
         * 班级控件的初始化
         */
        showGrade = getLayoutInflater().inflate( R.layout.show_grade_view, null);
        mGradeName = showGrade.findViewById(R.id.grade_name);
        mGradeTeach = showGrade.findViewById(R.id.grade_teach);
        mGradeEnter = showGrade.findViewById(R.id.grade_enter);
        mGradeCancel = showGrade.findViewById(R.id.grade_cancel);

        /**
         * 学生控件的初始化
         */
        showStudent = getLayoutInflater().inflate(R.layout.show_student_view, null);
        mStudentName = showStudent.findViewById(R.id.student_name);
        mStudentAge = showStudent.findViewById(R.id.student_age);
        mStudentSex = showStudent.findViewById(R.id.student_sex);
        mStudentLike = showStudent.findViewById(R.id.student_like);
        mStudentEnter = showStudent.findViewById(R.id.student_enter);
        mStudentCancel = showStudent.findViewById(R.id.student_cancel);

        /**
         * 教师控件的初始化
         */
        showTeacher = getLayoutInflater().inflate(R.layout.show_teach_view, null);
        mTeachName = showTeacher.findViewById(R.id.teach_name);
        mTeachAge = showTeacher.findViewById(R.id.teach_age);
        mTeachSex = showTeacher.findViewById(R.id.teach_sex);
        mTeachClass = showTeacher.findViewById(R.id.teach_class);
        mTeachEnter = showTeacher.findViewById(R.id.teach_enter);
        mTeachCancel = showTeacher.findViewById(R.id.teach_cancel);

    }

    /**
     * 控件的点击事件
     * @param v
     */
    @Override
    public void onClick(View v) {

        switch ( v.getId()) {
            // 录入信息
            case R.id.main_grade_insert:
                showPPW(ConstantEnum.grade);
                break;
            case R.id.main_teach_insert:
                showPPW(ConstantEnum.teacher);
                break;
            case R.id.main_student_insert:
                showPPW(ConstantEnum.student);
                break;
                // 查询信息
            case R.id.main_grade_show:
                query( ConstantEnum.grade);
                break;
            case R.id.main_teach_show:
                query(ConstantEnum.teacher);
                break;
            case R.id.main_student_show:
                query(ConstantEnum.student);
                break;
                // 确认信息
            case R.id.grade_enter:
                insert( ConstantEnum.grade);
                break;
            case R.id.teach_enter:
                insert( ConstantEnum.teacher);
                break;
            case R.id.student_enter:
                insert( ConstantEnum.student);
                break;
            // ppw 的取消
            case R.id.teach_cancel:
                teachDialog.dismiss();
                break;
            case R.id.grade_cancel:
                gradeDialog.dismiss();
                break;
            case R.id.student_cancel:
                studentDialog.dismiss();
                break;
        }
     }

     private void insert(ConstantEnum constant) {
     String name = null;
     String id = null;
     String sex = null;
     String age = null;
     String like = null;

     // 开启事务
     writaDb.beginTransaction();;
     switch ( constant) {
        case grade:

             name = mGradeName.getText().toString();
             like = mGradeTeach.getText().toString();

             if( "".equals( name) || "".equals(like)) {
                 Toast.makeText(this, "所填信息不能为空", Toast.LENGTH_SHORT).show();
                 return;
             }
             Cursor cursor = writaDb.rawQuery("select t_id from teacher where t_teach = " + like, null);

             if( cursor.moveToNext()) {
                 id = cursor.getColumnName(0);
                 ContentValues values = new ContentValues();
                 values.put("g_name", name);
                 values.put("g_t_id", id);
                 // 数据库事务判断数据是否插入
                 writaDb.setTransactionSuccessful();
                 writaDb.insert( "grade", null, values);
                 Toast.makeText(this,  like + "教师代课班级为" + name + "班级", Toast.LENGTH_SHORT).show();

                 mGradeTeach.setText("");
                 mGradeName.setText("");
                 gradeDialog.dismiss();
             }
             else {
                 Toast.makeText(this, "查询不到此老师，请重新填写", Toast.LENGTH_SHORT).show();
                 mGradeTeach.setText("");
                 mGradeName.setText("");
             }
             cursor.close();
            break;
        case teacher:

             name = mTeachName.getText().toString();
             sex = mTeachSex.getText().toString();
             age = mTeachAge.getText().toString();
             like = mTeachClass.getText().toString();

             if( "".equals( name) || "".equals( sex) || "".equals(age) || "".equals(like)) {
                 Toast.makeText(this, "所填信息不能为空", Toast.LENGTH_SHORT).show();
                 return;
             }

             ContentValues tValues = new ContentValues();
             tValues.put( "t_name", name);
             tValues.put( "t_sex", sex);
             tValues.put( "t_age", age);
             tValues.put( "t_teach", like);
             // 数据库事务判断数据是否插入
             writaDb.setTransactionSuccessful();
             writaDb.insert( "teacher", null, tValues);
             Toast.makeText(this, "教师信息存储成功", Toast.LENGTH_SHORT).show();

             mTeachName.setText("");
             mTeachAge.setText("");
             mTeachClass.setText("");
             mTeachSex.setText("");
             teachDialog.dismiss();
             break;
         case student:

             name = mStudentName.getText().toString();
             sex = mStudentSex.getText().toString();
             age = mStudentAge.getText().toString();
             like = mStudentLike.getText().toString();

             if( "".equals( name) || "".equals( sex) || "".equals(age) || "".equals(like)) {
                Toast.makeText(this, "所填信息不能为空", Toast.LENGTH_SHORT).show();
                return;
             }

             ContentValues sValues = new ContentValues();
             sValues.put( "s_name", name);
             sValues.put( "s_sex", sex);
             sValues.put( "s_age", age);
             sValues.put( "s_like", like);
             // 数据库事务判断数据是否插入
             writaDb.setTransactionSuccessful();
             writaDb.insert( "student", null, sValues);
             Toast.makeText(this, "学生信息存储成功", Toast.LENGTH_SHORT).show();

             mStudentName.setText("");
             mStudentSex.setText("");
             mStudentAge.setText("");
             mStudentLike.setText("");
             studentDialog.dismiss();
             break;
        }

         // 关闭事务
         writaDb.endTransaction();
    }

     /**
     * 查询数据
     * @param constant
     */
    private void query(ConstantEnum constant) {
        List<String> list = new ArrayList<>();
        Cursor cursor = null;
        try {
            switch (constant) {
                case grade:

                    cursor = writaDb.rawQuery("select grade.g_id, grade.g_name, student.s_name, teacher.t_name from crew , grade, student, teacher where crew.g_id = grade.g_id and crew.t_id = teacher.t_id and crew.s_id = student.s_id group by grade.g_id order by grade.g_id asc", null);
                    list.add( "班级ID 查询班级 代课老师 以及学生 ");
                    while ( cursor.moveToNext()) {
                        String line = cursor.getString(0) + "     " + cursor.getColumnName(1) + "     " + cursor.getString(2) + " " + cursor.getString(3);
                        list.add( line );
                    }
                    break;
                case teacher:

                    cursor = writaDb.rawQuery("select teacher.t_id, teacher.t_name from teacher order by teacher.t_id asc", null);
                    list.add( "查询的教师信息");
                    while ( cursor.moveToNext()) {
                        String line = cursor.getString(0) + "     " + cursor.getString(1);
                        list.add( line );
                    }
                    break;
                case student:

                    cursor = writaDb.rawQuery("select student.s_id, student.s_name from student order by student.s_id asc", null);
                    list.add( "查询的学生信息");
                    while ( cursor.moveToNext()) {
                        String line = cursor.getString(0) + "     " + cursor.getString(1);
                        list.add( line );
                    }
                    break;
            }
        }
        finally {
            if( cursor != null) {
                cursor.close();
            }
            adapter.refresh( list);
        }

    }

    /**
     * 弹出对应的信息视图
     */
    private void showPPW(ConstantEnum constant) {

        // 选择弹出的视图
        switch ( constant) {
            case grade:
                if( gradeDialog == null) {
                    gradeDialog = new AlertDialog.Builder(this).create();
                    gradeDialog.setView( showGrade);
                }
                gradeDialog.show();

                break;
            case student:

                if( studentDialog == null) {
                    studentDialog = new AlertDialog.Builder(this).create();
                    studentDialog.setView( showStudent);
                }
                studentDialog.show();
                break;
            case teacher:

                if( teachDialog == null) {
                    teachDialog = new AlertDialog.Builder(this).create();
                    teachDialog.setView( showTeacher);
                }
                teachDialog.show();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        writaDb.close();
    }
}
